<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<style type="text/css">
div{width: 100px; height: 100px; background-color: red;position: absolute; top: 50px;left: 20px;}
</style>
<script type="text/javascript">
window.onload = function () {
	var oDiv = document.getElementById('div1');
	var oInp = document.getElementById('input1');

	oInp.onclick = function (){
		doMove(oDiv,'left',20,800);
	}
}

function getStyle(obj,attr){
	return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj)[attr];
}

function doMove(obj,attr,dir,target,endFn){
			//var timer = null;		//设置局部变量而且是事件内部的局部变量时，需要特别小心是不是每次发生事件都需要将该变量重置
			if (obj.go) {return};
			obj.go = true;			//防止下面动态定位

			dir = parseInt(getStyle(obj,attr)) < 800 ? dir : -dir;	//判断前进方向	(parseInt()是动态的，会有隐患，所以需要上面解决)
			if(dir<0) {
				target = 20;		//返回
			}else{
				target = 800;		//前进
			};

			clearInterval(obj.timer);
			obj.timer = setInterval(function(){
				var speed = parseInt(getStyle(obj,attr)) + dir;

				if ( speed > target && dir >0 || speed < target && dir < 0) {
					speed = target;
				};
				obj.style[attr] = speed + 'px';
				if (speed == target) {
					clearInterval(obj.timer);
					endFn && endFn();
					obj.go = false;
				};
			},20)
		}
</script>
<body>
	<input id="input1" type="button" value="移动" />
	<div id="div1"></div>
</body>
</html>